package de.szut.traineeslife.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;

import android.net.Uri;
import android.util.Log;

import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpResponse;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.Drive.Children;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.Drive.Files.Insert;
import com.google.api.services.drive.model.ChildList;
import com.google.api.services.drive.model.ChildReference;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
import com.google.api.services.drive.model.ParentReference;

public class DriveHelper {

	private String APP_FOLDER = "Trainees Life";
	private String APP_FOLDER_ID;

	public String getAPP_FOLDER_ID() {
		return APP_FOLDER_ID;
	}

	public void setAPP_FOLDER_ID(String aPP_FOLDER_ID) {
		APP_FOLDER_ID = aPP_FOLDER_ID;
	}

	/**
	 * Checks which type of Document the current File is, converts the File to a
	 * drive-file and loads the file up via a Drive-service
	 * 
	 * @param fileUri
	 * @param service
	 * @param helper
	 */
	public File saveFileToDrive(final Uri fileUri, Drive service, FileHelper helper, String fileName) {
		File driveFile = null;
		try {
			FileContent mediaContent = null;
			java.io.File fileContent = new java.io.File(fileUri.getPath());
			if (fileContent.getName().endsWith(".odt")) {
				mediaContent = new FileContent("application/vnd.oasis.opendocument.text", fileContent);
			} else if (fileContent.getName().endsWith(".doc") || fileContent.getName().endsWith(".docx")) {
				mediaContent = new FileContent("application/vnd.openxmlformats-officedocument.wordprocessingml.document", fileContent);
			} else if (fileContent.getName().endsWith(".pdf")) {
				mediaContent = new FileContent("application/pdf", fileContent);
			} else if (fileContent.getName().endsWith(".html")) {
				mediaContent = new FileContent("text/html", fileContent);
			}
			if (mediaContent != null) {
				com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File();
				// String fileName = "";
				// for (String end : helper.getEndings()) {
				// if (fileUri.getPath().toLowerCase().endsWith(end)) {
				// fileName = fileContent.getName().replaceAll(end, "");
				// }
				// }
				body.setTitle(fileName);
				body.setParents(Arrays.asList(new ParentReference().setId(getAPP_FOLDER_ID())));
				Insert request = service.files().insert(body, mediaContent);
				request.setConvert(true);
				driveFile = request.execute();
			}
		} catch (UserRecoverableAuthIOException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return driveFile;

	}

	/**
	 * Gets an Arraylist of all existing Folders in Drive
	 * 
	 * @param service
	 * @return
	 * @throws IOException
	 */
	public ArrayList<File> getDrivesFolderList(Drive service) throws IOException {
		ArrayList<File> driveFiles = new ArrayList<File>();
		Files.List request = service.files().list().setQ("mimeType='application/vnd.google-apps.folder' and trashed=false");
		do {
			try {

				FileList folderList = request.execute();
				driveFiles.addAll(folderList.getItems());
				request.setPageToken(folderList.getNextPageToken());
			} catch (IOException e) {
				e.printStackTrace();
				request.setPageToken(null);
			}
		} while (request.getPageToken() != null && request.getPageToken().length() > 0);
		// for(File f : driveFiles){
		// Log.d(f.getTitle(),f.getId());
		// }
		return driveFiles;
	}

	/**
	 * Checks if the App-folder alway exists
	 * 
	 * @param driveFiles
	 * @return
	 */
	public String checkForAppFolder(ArrayList<File> driveFiles) {
		File folder = null;
		for (File file : driveFiles) {
			if (file.getTitle().equals(APP_FOLDER)) {
				folder = file;
				setAPP_FOLDER_ID(folder.getId());
				return folder.getId();
			}
			// }
			// if (folder != null && folder.getTitle().equals(APP_FOLDER)) {
			// setAPP_FOLDER_ID(folder.getId());
			// return folder;
		}
		return "";
	}

	/**
	 * Creates the App-Folder in Drive if it not exist
	 * 
	 * @param service
	 * @param folder
	 * @return
	 */
	public boolean createAppFolder(Drive service, String folderID) {
		File f = new File().setId(folderID);
		com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File();
		body.setTitle(APP_FOLDER);
		body.setMimeType("application/vnd.google-apps.folder");
		Insert insert;
		try {
			insert = service.files().insert(body);
			f = insert.execute();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		setAPP_FOLDER_ID(f.getId());
		return true;

	}

	// TO DO - LÄUFT NISCHT
	/**
	 * Gets List of all Files in Drive
	 * 
	 * @param service
	 * @return
	 * @throws IOException
	 */
	public ArrayList<File> getModelFromDrive(Drive service) throws IOException {
		ArrayList<File> driveFiles = new ArrayList<File>();
		Files.List request = service.files().list().setQ("title ='TraineesLife_Vorlage' and trashed=false");
		do {
			try {
				FileList fileList = request.execute();
				driveFiles.addAll(fileList.getItems());
				request.setPageToken(fileList.getNextPageToken());
			} catch (IOException e) {
				e.printStackTrace();
				request.setPageToken(null);
			}
		} while (request.getPageToken() != null && request.getPageToken().length() >0);
		return driveFiles;
	}

	// File folder = new File().setId(getAPP_FOLDER_ID());
	// Children.List request = service.children().list(getAPP_FOLDER_ID());
	// do {
	// try {
	//
	// ChildList childList = request.execute();
	// for(ChildReference child : childList.getItems()){
	// Log.d("CHILDLIST",child.toString());
	// driveFiles.add(new File().setId(child.getId()));
	// }
	// request.setPageToken(childList.getNextPageToken());
	// } catch (IOException e) {
	// e.printStackTrace();
	// request.setPageToken(null);
	// }
	// } while (request.getPageToken() !=null && request.getPageToken().length()
	// > 0);

	public InputStream downlaodFileFromDrive(Drive service, String fileID) {
		File downloadFile = null;
		try {
			downloadFile = service.files().get(fileID).execute();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (downloadFile != null) {
			if (downloadFile.getDownloadUrl() != null && downloadFile.getDownloadUrl().length() > 0) {
				try {
					HttpResponse response = service.getRequestFactory().buildGetRequest(new GenericUrl(downloadFile.getDownloadUrl())).execute();
					Log.d("DOWNLOADFROMDRIVE", response.getContent().toString());
					return response.getContent();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		Log.d("DOWNLOADFROMDRIVE", "NULL");
		return null;
	}
}
